package com.qf.myshop.utils;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * 数据库连接类
 */
public class JDBCUtils {
    private static final Properties PROPERTIES = new Properties();
    private static final ThreadLocal<Connection> THREAD_LOCAL = new ThreadLocal<>();
    private static DataSource dataSource = new ComboPooledDataSource();;
    static {
        try {
            dataSource = new ComboPooledDataSource();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() throws SQLException {
        Connection connection = THREAD_LOCAL.get();
        if (connection == null || connection.isClosed()){
            connection = dataSource.getConnection();
            THREAD_LOCAL.set(connection);
        }
        return connection;
    }

    public static void close()throws SQLException{
        Connection connection = THREAD_LOCAL.get();
        if (connection != null){
            connection.close();
            THREAD_LOCAL.remove();
        }
    }
}
